﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NCS.IConnect.ApplicationContexts;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using Microsoft.SharePoint;
using System.Collections;
using JM.JCY.Common;

namespace JM.JCY.SharePointComponent.Committee.EditCommitteeMember
{
    public partial class EditCommitteeMemberUserControl : UserControl
    {
        static string JCYUrl = System.Configuration.ConfigurationManager.AppSettings["JCYUrl"].ToString();
        public int _userId
        {
            set { ViewState["_userId"] = value; }
            get { return (int)ViewState["_userId"]; }
        }

        public int _committeeId
        {
            set { ViewState["_committeeId"] = value; }
            get { return (int)ViewState["_committeeId"]; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (ApplicationContext.Current.GetKeyValue("userId") != null)
            {
                _userId = Int32.Parse(ApplicationContext.Current.GetKeyValue("userId").ToString());
            }
            string removeUser = Request.Params.Get("__EVENTTARGET");
            if (!IsPostBack)
            {

                if (Request.QueryString["CommitteeId"] != null)
                {
                    _committeeId = Int32.Parse(Request.QueryString["CommitteeId"]);
                }
                using (UserManagementProxy userProxy = new UserManagementProxy())
                {

                    // load for committee info
                    CommitteeDataSet.T_CommitteeDataTable committeeDT = userProxy.GetCommitteeById(_committeeId);
                    if (committeeDT.Rows.Count > 0)
                    {
                        this.lblName.Text = committeeDT[0].CommitteeName;
                        this.ttaDesc.InnerHtml = committeeDT[0].CommitteeDescription;
                    }

                    Session["CommitteeDT"] = committeeDT.Copy();
                    // load for member list box
                    DataSetUserManagement.T_UserInfoDataTable userDT = userProxy.GetUser(0, string.Empty);
                    CommitteeDataSet.T_Committee_MemberDataTable memberDT = userProxy.GetCommitteeMember(_committeeId);
                    Session["MemberDT"] = memberDT.Copy();
                    foreach (CommitteeDataSet.T_Committee_MemberRow userExist in memberDT.Rows)
                    {
                        for (int i = 0; i < userDT.Rows.Count; i++)
                        {
                            if (userDT[i]["ID"].Equals(userExist.UserId))
                            {
                                userDT.Rows.Remove(userDT[i]);
                            }
                        }
                    }
                    if (userDT.Rows.Count > 0)
                    {
                        box1View.DataSource = userDT;
                        box1View.DataTextField = "UserName";
                        box1View.DataValueField = "ID";
                        box1View.DataBind();
                    }

                    // bind box view for current members
                    box2View.DataSource = memberDT;
                    box2View.DataTextField = "UserName";
                    box2View.DataValueField = "UserId";
                    box2View.DataBind();
                }

            }
            if (removeUser != null && removeUser.IndexOf("DeleteCommittee") > -1)
            {
                imgRemove_Click(null, null);
            }
        }

        protected void imgSavePublish_Click(object sender, ImageClickEventArgs e)
        {
            SaveCommittee();
            Response.Redirect("/MyCommittee/default.aspx?CommitteeId=" + _committeeId);
        }

        protected void imgCancel_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("/MyCommittee/default.aspx?CommitteeId=" + _committeeId);
        }

        private void SaveCommittee()
        {
            using (UserManagementProxy proxy = new UserManagementProxy())
            {
                // update committee
                if (Session["CommitteeDT"] != null)
                {
                    var committeeDT = (CommitteeDataSet.T_CommitteeDataTable)Session["CommitteeDT"];
                    if (committeeDT.Rows.Count > 0)
                    {
                        committeeDT[0].CommitteeDescription = this.ttaDesc.InnerText;
                        committeeDT[0].IsDeleted = false;
                        JCY.Common.JCYUtility.UpdateCommonFields(committeeDT[0], "admin");
                        proxy.UpdateCommittee(committeeDT);
                    }
                }

                var arrUserCol = new ArrayList();
                SPWeb web = SPContext.Current.Web;
                var newMemberDT = new CommitteeDataSet.T_UserCommitteeDataTable();

                // update committee member
                if (Session["MemberDT"] != null)
                {
                    var oldDT = (CommitteeDataSet.T_Committee_MemberDataTable)Session["MemberDT"];
                    foreach (CommitteeDataSet.T_Committee_MemberRow oldRow in oldDT.Rows)
                    {
                        // delete all old data
                        var deleteDT = proxy.GetUserCommitteeById(oldRow.UserCommitteeId);
                        deleteDT[0].IsDeleted = true;
                        JCY.Common.JCYUtility.UpdateCommonFields(deleteDT[0], "admin");
                        proxy.UpdateUserComittee(deleteDT);

                        // remove old users
                        SPUser spUser = web.EnsureUser(oldRow.UserName);
                        RemoveUserFromGroup(spUser, this.lblName.Text);
                    }

                    // add new data
                    string s = Request.Form[box2View.UniqueID];

                    foreach (var item in s.Split(','))
                    {
                        if (Int32.Parse(item) != _userId)
                            AddUserToCommittee(newMemberDT, Int32.Parse(item), _committeeId, false);
                        else
                            AddUserToCommittee(newMemberDT, Int32.Parse(item), _committeeId, true);

                        // add users into group
                        string selectUser = proxy.GetUser(Int32.Parse(item), string.Empty)[0].UserName;
                        SPUser spUser = web.EnsureUser(selectUser);
                        AddUserToGroup(spUser, this.lblName.Text);

                        // add all user into arr
                        arrUserCol.Add(item);
                    }

                    // check whether creator is in list
                    if (!arrUserCol.Contains(_userId.ToString()))
                    {
                        AddUserToCommittee(newMemberDT, _userId, _committeeId, true);
                        // add user into group
                        string selectUser = proxy.GetUser(_userId, string.Empty)[0].UserName;
                        SPUser spUser = web.EnsureUser(selectUser);
                        AddUserToGroup(spUser, this.lblName.Text);
                    }
                    proxy.UpdateUserComittee(newMemberDT);
                }
            }

        }

        public void RemoveUserFromGroup(SPUser user, string groupname)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
              {
                  using (SPSite site = new SPSite(JCYUrl))
                  {
                      using (SPWeb web = site.AllWebs[JCYConstant.SiteName.MyCommittee])
                      {
                          if (IsExistUser(user, groupname))
                          {
                              web.AllowUnsafeUpdates = true;
                              web.SiteGroups[groupname].RemoveUser(user);
                              web.AllowUnsafeUpdates = false;
                          }
                      }
                  }
              });
        }

        public bool IsExistUser(SPUser user, string groupname)
        {
            bool exist = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.AllWebs[JCYConstant.SiteName.MyCommittee])
                    {
                        SPUserCollection users = web.SiteGroups[groupname].Users;
                        foreach (SPUser userlist in users)
                        {
                            if (userlist.ToString().ToLower() == user.LoginName.ToLower())
                                exist = true;
                        }
                    }
                }
            });


            return exist;

        }

        public void AddUserToGroup(SPUser user, string groupname)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.AllWebs[JCYConstant.SiteName.MyCommittee])
                    {
                        web.AllowUnsafeUpdates = true;
                        if (!IsExistUser(user, groupname))
                        {

                            web.SiteGroups[groupname].AddUser(user);
                        }
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
        }
    

        private void AddUserToCommittee(CommitteeDataSet.T_UserCommitteeDataTable newMemberDT, int userId, int committeeId, bool isAdmin)
        {
            var memberRow = newMemberDT.NewT_UserCommitteeRow();
            memberRow.UserId = userId;
            memberRow.CommitteeId = committeeId;
            if (isAdmin)
                memberRow.IsAdmin = true;
            else
                memberRow.IsAdmin = false;
            memberRow.IsDeleted = false;
            JCY.Common.JCYUtility.UpdateCommonFields(memberRow, "admin");
            newMemberDT.AddT_UserCommitteeRow(memberRow);

        }

        protected void imgRemove_Click(object sender, ImageClickEventArgs e)
        {
            using (UserManagementProxy proxy = new UserManagementProxy())
            {
                var removeDT = proxy.GetCommitteeById(_committeeId);

                DeleteDocLibrary(removeDT[0].CommitteeName);
                DeleteDocLibrary(removeDT[0].CommitteeName + " 讨论版");
                // remove user committee
                CommitteeDataSet.T_Committee_MemberDataTable oldDT = proxy.GetCommitteeMember(_committeeId);
                foreach (CommitteeDataSet.T_Committee_MemberRow oldRow in oldDT.Rows)
                {
                    // delete all old data
                    var deleteDT = proxy.GetUserCommitteeById(oldRow.UserCommitteeId);
                    deleteDT[0].IsDeleted = true;
                    JCY.Common.JCYUtility.UpdateCommonFields(deleteDT[0], "admin");
                    proxy.UpdateUserComittee(deleteDT);

                }
                // remove committee
                removeDT[0].IsDeleted = true;
                JCY.Common.JCYUtility.UpdateCommonFields(removeDT[0], "admin");
                proxy.UpdateCommittee(removeDT);

            }
            Response.Redirect(SPContext.Current.Web.ParentWeb.Url);

        }

        private void DeleteDocLibrary(string docName)
        {
           

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb myWeb = site.AllWebs[JCYConstant.SiteName.MyCommittee])
                    {
                        myWeb.AllowUnsafeUpdates = true;

                        // delete old doc and old group
                        SPList oldDept = myWeb.Lists[docName];

                        oldDept.BreakRoleInheritance(true);
                        SPRoleAssignmentCollection assignmentColOld = oldDept.RoleAssignments;
                        for (int i = assignmentColOld.Count - 1; i >= 0; i--)
                        {
                            assignmentColOld.Remove(i);
                        }
                        myWeb.SiteGroups.Remove(docName);
                        myWeb.Update();
                        myWeb.Lists.Delete(oldDept.ID);
                        myWeb.AllowUnsafeUpdates = false;
                    }
                }
            });

        }
    }
}
